package com.chemical.search.view.manage;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.chemical.search.dto.QueryUserDTO;
import com.chemical.search.model.Menu;
import com.chemical.search.model.UserGroup;
import com.chemical.search.model.UserInfo;
import com.chemical.search.service.IUserManageService;
import com.chemical.search.util.common.EncodeUtil;
import com.chemical.search.util.page.Condition;
import com.chemical.search.util.page.Page;
import com.chemical.search.util.page.PageUtil;
import com.chemical.search.util.query.PropertyFilter;
import com.chemical.search.view.BaseController;

/**
 *@className:UserController.java
 *@classDescription:
 *@author:MChen
 *@createTime:2012-4-20
 */
@Controller
@RequestMapping("/manage/user")
public class UserController extends BaseController{
	
	Page<UserInfo> page = new Page<UserInfo>(10);
	@Autowired
	protected IUserManageService userManageService ;
	
	/**
	 * 用户后台登录
	 * @param model
	 * @param user
	 * @param request
	 * @return
	 */
	@RequestMapping("managelogin")
	@SuppressWarnings("unchecked")
	public String manageLogin(Model model, UserInfo user, HttpServletRequest request) {
		UserInfo userinfo = this.userManageService.login(user);
		if(null != userinfo){
			int group = userinfo.getUserGroup().getGroup_id();
			if(group !=1 && group !=2 ){
				model.addAttribute("msg", "sorry,你没有权限访问");
				return "/manage/login.jsp";
			}
			else{
				//将用户拥有的菜单显示出来
				Map menuMap = new HashMap();
				UserGroup role = userinfo.getUserGroup();
				for (Menu menu : role.getMenus()) {
					if (!menuMap.containsKey(menu.getFunction_id())) {
						menuMap.put(menu.getFunction_id(), menu);
					}
				  }
				request.getSession().setAttribute("userMenuMap", menuMap);
				request.getSession().setAttribute("userInfo", userinfo);
				return "/manage/index/index.jsp";
			}
		}
		else{
			model.addAttribute("msg", "用户名或者密码错误");
			return "/manage/login.jsp";
		}
	}
	
	/**
	 * 用户前台登录
	 * @param model
	 * @param user
	 * @param request
	 * @return
	 */
	@RequestMapping("login")
	public String login(Model model,UserInfo user, HttpServletRequest request,HttpServletResponse response){
		//获取session
		HttpSession session = request.getSession();
		if(session.getAttribute("userLogin") == null){
			if(user!=null){
				UserInfo userinfo = this.userManageService.login(user);
				if(userinfo != null){
					request.getSession().setAttribute("userLogin", userinfo);
					System.out.println("登陆成功"+user.getUser_name()+"====="+user.getUser_password());
					try {
						response.sendRedirect(request.getContextPath()+"/structure_search.jsp");
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				else{
					try {
						response.sendRedirect(request.getContextPath()+"/login.jsp");
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		//如果session里面没有值的话,跳转到登录页面
		else{
			 try {
				response.sendRedirect(request.getContextPath()+"/login.jsp");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 用户登出
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/loginOut")
	public String loginOut(HttpServletRequest request,HttpServletResponse response) {
		String url = request.getParameter("url");
		//销毁session
		request.getSession().removeAttribute("userLogin");
		request.getSession().invalidate();
		if(url != null){
			System.out.println(url.trim());
			try {
				response.sendRedirect(url.trim());
			} catch (Exception e) {
//				e.printStackTrace();
			}
		}
		return "manage/login.jsp";
	}
	
	@RequestMapping(value = "/new")
	public String newUser(HttpServletRequest request,Model model){
		return "manage/user/addUser.jsp";
	}
	
	/**
	 * 添加用户
	 * @param model
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/add")
	public String add(Model model,UserInfo user,HttpServletRequest request,HttpServletResponse response){
		if(user != null){
			int groupId = Integer.parseInt(request.getParameter("groupMode"));
			UserGroup group = new UserGroup();
			group.setGroup_id(groupId);
			user.setUserGroup(group);
			user.setAllowvisit(1);
			if(this.userManageService.save(user)){
//				System.out.println("添加用户成功");
				String currentPage = (String) this.getSessionAttribute(request,"currentPage");
				this.sendRedirect(response, currentPage);
				return "manage/user/addUser.jsp";
			}
		}
			model.addAttribute("msg", "增加用户失败");
			return "manage/user/addUser.jsp";
	}
	
	/**
	 * 删除用户
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete/{id}")
	public String delete(@PathVariable int id, HttpServletRequest request,
			HttpServletResponse response) {
		this.userManageService.deleteById(id);
		String currentPage = (String) this.getSessionAttribute(request,
				"currentPage");
		this.sendRedirect(response, currentPage);
		return null;
	}
	
	@RequestMapping(value = "/editPwd")
	public String editPwd(HttpServletRequest request,Model model){
		return "manage/user/editpassword.jsp";
	}
	
	/**
	 * 编辑用户信息
	 * @param model
	 * @param userInfo
	 * @param result
	 * @return
	 */
	@RequestMapping(value = "/edit/{id}")
	public String edit(Model model, @PathVariable("id") int id) {
		UserInfo user = this.userManageService.findById(id);
		model.addAttribute("userInfo", user);
		return "manage/user/alterUser.jsp";
	}
	
	/**
	 * 修改密码
	 * @参数： @param model
	 * @参数： @param user
	 * @参数： @return    
	 * @return String   
	 * @throws
	 */
	@RequestMapping(value = "/modifypwd")
	public String modifyPwd(Model model, HttpServletRequest request,HttpServletResponse response) {
		String repassword = request.getParameter("user_password");
		// 修改成功重新登录
		UserInfo userinfo = (UserInfo) request.getSession().getAttribute( "userInfo");
		userinfo.setUser_password(repassword);
		this.userManageService.update(userinfo);
		return "/manage/user/loginOut.do";
	}
	
	/**
	 * 修改用户
	 * 
	 * @param model
	 * @param userInfo
	 * @param result
	 * @return
	 */
	@RequestMapping(value = "/update")
	public String update(UserInfo userInfo, HttpServletRequest request,HttpServletResponse response) {
		UserInfo user = this.userManageService.findById(userInfo.getUser_id());
		int groupId = Integer.parseInt(request.getParameter("groupMode"));
		user.setUser_password(userInfo.getUser_password());
		UserGroup group = new UserGroup();
		group.setGroup_id(groupId);
		user.setUserGroup(group);
		user.setUser_email(userInfo.getUser_email());
		
		this.userManageService.update(user);
		String currentPage = (String) this.getSessionAttribute(request,
				"currentPage");
		System.out.println(currentPage);
		this.sendRedirect(response, currentPage);
		return null;
	}
	
	/**
	 * 检查用户是否可用
	 * @param userName
	 * @param respnose
	 */
	@RequestMapping("/checkUserName")
	public void checkUserName(String userName, HttpServletResponse respnose) {
		PrintWriter out = null;
		boolean flag = this.userManageService.checkUserName(userName);
		try {
			out = respnose.getWriter();
			if (flag) {
				out.print("1");
			} else {
				out.print("0");
			}
			out.flush();
			out.close();
		} catch (Exception e) {
			System.out.println("user check error......");
		} finally{
			if(null != out){
				out.close();
			}
		}
	}
	
	/**
	 * 显示所有的用户
	 * @return
	 */
	@RequestMapping(value = { "/list", "" })
	@SuppressWarnings("unchecked")
	public String list(QueryUserDTO userDTO, Model model, HttpServletRequest request) {
		// fileds
		String userName = userDTO.getKey();
		int pageNo = userDTO.getPageNo();
		String order = userDTO.getOrder();
		String startDate = userDTO.getStartDate();
		String endDate = userDTO.getEndDate();

		// 查询条件
		PropertyFilter pf = new PropertyFilter("user_name:LIKE_S", userName);
		PropertyFilter startPf = new PropertyFilter("user_addTime:GT_D",
				startDate);
		PropertyFilter endPf = new PropertyFilter("user_addTime:LT_D", endDate);
		List<PropertyFilter> pfList = new ArrayList<PropertyFilter>();
		pfList.add(pf);
		pfList.add(startPf);
		pfList.add(endPf);

		// 设置跳转页面
		StringBuffer forwordName = new StringBuffer(this.getRoot(request)
				+ "/manage/user/list.do");

		// 获取分页跳转页面
		List<Condition> fragmentList = new ArrayList();
	
		fragmentList.add(new Condition("key", EncodeUtil.urlEncode(userName), "匹配'" + userName
				+ "'"));
		fragmentList.add(new Condition("order", order, "排序", false));
		fragmentList
				.add(new Condition("startDate", startDate, "大于" + startDate));
		fragmentList.add(new Condition("endDate", endDate, "小于" + endDate));

		String forwarCondition = PageUtil.getForwardCondition(fragmentList);
		forwordName.append(forwarCondition);
		// 获取排序跳转页面
		String orderCondition = PageUtil.getOrderCondition(fragmentList);
		model.addAttribute("order", orderCondition);

		// 获取过滤查询集合
		List<Condition> filterList = PageUtil.getFilterConditions(fragmentList);
		model.addAttribute("filterList", filterList);

		// 初始化page属性值--默认id排序
		if (null == order) {
			page.setOrder("id:asc");
		} else {
			page.setOrder(order);
		}
		page.setPageNo(pageNo);
		// 查询所有用户，并放入会话
		page = this.userManageService.findAllUsers(page, pfList);
		model.addAttribute("userList", page.getResult());
		// 生成分页标签
		page.setForwordName(forwordName.toString());
		String tag = PageUtil.getTag(page);
		model.addAttribute("tag", tag);
		// 索引号
		model.addAttribute("index", page.getFirst());

		// 设置页面搜索初始值
		model.addAttribute("key", userName);
		model.addAttribute("startDate", startDate);
		model.addAttribute("endDate", endDate);

		String currentPage = request.getRequestURI().toString()
				+ forwarCondition + page.getPageNo();
		
		request.getSession().setAttribute("currentPage", currentPage);
		return "manage/user/userManage.jsp";
	}
}
